import vtkmodules.all as vtk
from CloudEngine.core.SphereActor import SphereActor


class LabelActor:
    created_by = 'default'
    type = 'LABEL'
    options = dict()
    start = [0, 0, 0]
    ref_renderer = None
    height = 0

    def __init__(self, start, options={}):
        self.instance = vtk.vtkTextActor()
        self.options = options
        self.start = start
        self.hide = SphereActor(start, {'radius': 0.1, 'color': [0, 1, 0]})
        self.hide.setPosition(start)
        self.hide.setVisible(False)
        self.text("")
        self.initOptions()

    def initOptions(self):
        if self.options.get('text') is not None:
            self.text(self.options.get('text'))

        self.instance.GetTextProperty().SetColor(self.options.get('color', [1, 0, 0]))

    def text(self, text):
        self.instance.SetInput(text)

    def compute_world_to_display(self, renderer, x, y, z):
        renderer.SetWorldPoint(x, y, z, 1.0)
        renderer.WorldToDisplay()
        return renderer.GetDisplayPoint()

    def update(self):
        x, y, z = self.hide.center
        r = self.compute_world_to_display(self.ref_renderer, x, y, z)
        ap = vtk.vtkRenderWindow().GetDPI() / 72
        self.updateScreenPosition([r[0] / ap, self.height - r[1] / ap])

    def mount(self, renderer, height):
        self.ref_renderer = renderer
        self.height = height
        r = self.compute_world_to_display(renderer, self.start[0], self.start[1],
                                          self.start[2])
        ap = vtk.vtkRenderWindow().GetDPI() / 72
        self.updateScreenPosition([r[0] / ap, self.height - r[1] / ap])

    def updateScreenPosition(self, start):
        self.instance.SetDisplayPosition(int(start[0]), int(start[1]))

    def getFlag(self):
        return self.hide
